package com.dhgate.spu.analysis.stat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.text.ParseException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.synonym.SolrSynonymParser;
import org.apache.lucene.analysis.synonym.SynonymFilter;
import org.apache.lucene.analysis.synonym.SynonymMap;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.util.Version;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dhgate.spu.analysis.consts.SysConsts;
import com.dhgate.spu.analysis.dao.DAOFactory;
import com.dhgate.spu.analysis.init.InitDbConfig;

public class CopyOfAttrMatchMain {
	private static final Logger log = LoggerFactory.getLogger(CopyOfAttrMatchMain.class);
	public static void main(String[] args) throws Exception {
		
		//初始化基本配置参数
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File(SysConsts.CONST_PARAMXML_PATH));
		SysConsts.DAO_NAME = document.getRootElement().element("DAO").getTextTrim();
		System.out.println("DAO_NAME: "+SysConsts.DAO_NAME);
		//初始化数据来源
		DAOFactory.init();
		
		//读取数据库初始化配置
		InitDbConfig.init();
		
		System.out.println("数据库初始化完毕"); 
		
		System.out.println("============"+DAOFactory.getDAOInstance()+" ========"+DAOFactory.getDAOInstance().getAttrValMap("296289"));
		
		System.out.println("getAttrValMap(296289)获取完毕"); 
		
		//SpuStandardConsts.init();
		
		CopyOfAttrMatchMain am = new CopyOfAttrMatchMain();

		String sourcePath = "/spu/tianweilin/spu-analysis/spu_006014013.csv";     
		String targetPath = "/spu/tianweilin/spu-analysis/spu_006014013_ok.csv"; 
		
		am.putRequiredAttrVal(sourcePath,targetPath);									
	}
	
	/**
	 * 读取csv，选择合适属性值回填到csv
	 * @param sourcePath  csv源路径
	 * @param targetPath  输出路径
	 */
	public void putRequiredAttrVal(String sourcePath,String targetPath){
        BufferedReader br = null;
        String sCurrentLine;
        try {
			br = new BufferedReader(new FileReader(sourcePath));
			while((sCurrentLine = br.readLine()) != null){
	            System.out.println(sCurrentLine);
	            String[] split = sCurrentLine.split(",");
	            
	            //解决由于“，”分隔符引起的错误
	            int specialIndex = 0;
	            for(int i = 0;i < split.length;i++){
	            	if(split[i].indexOf("\"") != -1){
	            		specialIndex = i;
	            	}
	            } 
	            if(specialIndex != 0){
	            	for(int i=2;i <= specialIndex;i++){
	            		split[1] += " "+split[i]+" ";
	            	}
	            	
	            	split[3] = split[specialIndex + 2];
	            }
	            System.out.println();
	                        		            	
	            	//写数据
	            	String requiredAttrAppend = ","+" "+","+" "+","+"N"; 
	                FileWriter fw = new FileWriter(targetPath,true);//append true -->>new FileWrite(file,true);
	                BufferedWriter bw = new BufferedWriter(fw);
	                try {
	                	Map<String, String> attrvalMap = getAttrvalList(split[3]); //split[3]:attrId
	                	if(attrvalMap != null){
	                		String attrAppendTemp = null;
	                		for(String s:attrvalMap.keySet()){
	                			boolean isRequiredAttrVal = isRequiredAttrVal(split[1],attrvalMap.get(s));//split[1]:标题    
	                			if(isRequiredAttrVal){
	                				attrAppendTemp +=  ","+attrvalMap.get(s)+","+s+","+"Y";
	                				requiredAttrAppend = ","+attrvalMap.get(s)+","+s+","+"Y";
	                				break;
	                			}else{
	                				requiredAttrAppend = ","+" "+","+" "+","+"N";
	                			}
	                		}
	                		if(!StringUtils.isBlank(attrAppendTemp)){
	                			requiredAttrAppend = attrAppendTemp;
	                		}
	                		
	                	}else{
	                		requiredAttrAppend = ","+" "+","+" "+","+"N";
	                	}
						
					} catch (ParseException e) {
						requiredAttrAppend = ","+" "+","+" "+","+"Exception";
						e.printStackTrace();
					}
	                
	                bw.write(sCurrentLine+requiredAttrAppend+"\n"); 	                	                
	                bw.flush();
	                bw.close();
	            		            
	        }
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		
	}
	

	/**
	 * 判断属性是否是需要回填的数据
	 * @param title   产品标题
	 * @param attrVal   回填属性值
	 * @return
	 */
	public boolean isRequiredAttrVal(String title,String attrVal) throws IOException, ParseException{
		boolean isRequiredAttrVal = false;
		boolean dedup = true;
		boolean expand = false;
		
		if(title.toUpperCase().indexOf(attrVal.toUpperCase()) != -1){
			return true;
		}
		
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);
		SolrSynonymParser parser = new SolrSynonymParser(dedup, expand, analyzer);

		parser.add(new FileReader(new File(SysConsts.CONST_SYNOYM_FILE_PATH)));
		SynonymMap build = parser.build();
		
		StringReader reader = new StringReader(title);
		TokenStream ts = analyzer.tokenStream("", reader);

		SynonymFilter synonymFilter = new SynonymFilter(ts, build, true);
		CharTermAttribute term = synonymFilter.getAttribute(CharTermAttribute.class);
		synonymFilter.reset();
		//多词语比对
		String a[] = attrVal.split(" ");
		int flag = 0;
		while (synonymFilter.incrementToken()) {
			if(term.toString().equals(attrVal)){
				isRequiredAttrVal = true;
			}
			for(int i = 0;i < a.length;i++){
				if(term.toString().indexOf(a[i]) != -1){
					flag ++;
				}
			}
			if(flag >= a.length){
				isRequiredAttrVal = true;
			}
		}
		return isRequiredAttrVal;
	}		

	/**
	 * 获取AttrMap
	 * @param attrId  attrId
	 * @return key:attrValId   value:attrValName
	 */
	public Map<String, String> getAttrvalList(String attrId){

		Map<String, String> attrValMap = DAOFactory.getDAOInstance().getAttrValMap(attrId);
		log.info(attrId);
		return attrValMap;
	}
	
	//TODO 缺失的属性是否子属性
	
	
	
	//TODO　非二级属性
	
	
	
	
}
